﻿using HalconDotNet;
using Halcon二次开发.Model.储放所有单例.储存每个单例界面;
using Halcon二次开发.Tools;
using Halcon二次开发.View.Socket通信;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Halcon二次开发.Controller.通信
{
    /// <summary>
    /// Socket通信动作类,单例模式
    /// </summary>
    public class SocketController
    {
        /// <summary>
        /// 单例模式的Socket连接对象
        /// </summary>
        public Socket socket {  get; set; } 
        //动作类对象
        private static SocketController socketController;
        //消息存储(接收到的消息就在这里)
        public string messageString;
        //SocketForm窗体对象
        public SocketForm form;
        public static SocketController GetSocketController()
        {
            if (socketController == null)
            {
                socketController = new SocketController();
            }
            return socketController;
        }
        //将SocketForm窗体对象传进来
        public void SetSocketForm(SocketForm socketForm)
        {
            this.form = socketForm;
        }
        /// <summary>
        /// 连接方法
        /// </summary>
        /// <param name="ip">IP地址</param>
        /// <param name="addres">端口号</param>
        public bool Connect(string ip,string addres)
        {
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress Ip = IPAddress.Parse(ip);
                IPEndPoint point = new IPEndPoint(Ip, Convert.ToInt32(addres));
                socket.Connect(point);
                (FormDb.Db["Form1"] as Form1).textBox1.AppendText(HelpGetTiem.Getyyymmddmmss() + ":" + "Sokcet通信连接成功信息为：" +ip + "\r\n");
                Thread thread = new Thread(ReceiveThread);
                //设置为后台线程
                thread.IsBackground = true; 
                thread.Start();
                return true;
            }
            catch (Exception ex) 
            { 
                (FormDb.Db["Form1"] as Form1).textBox1.AppendText(HelpGetTiem.Getyyymmddmmss() + ":" + "Sokcet通信连接失败，请检查IP和端口号是否正确" + ip + "\r\n"); 
                return false;
            }
        }
        //建立接收数据的线程
        private void ReceiveThread()
        {
            while (true)
            {
                try
                {
                    byte[] bytes = new byte[1024 * 1024 * 3];
                    int r = socket.Receive(bytes);
                    if (r == 0)
                    {
                        break;
                    }
                    string str = Encoding.Default.GetString(bytes, 0, r);
                    messageString = str;
                    form.receiveTextBox.Text += messageString + "\r" + "\n";
                    form.listReceiveRecord.Add(HelpGetTiem.Getyyymmddmmss() + "-$&^&$-" + str);
                    form.dataGridView2.Rows.Add(HelpGetTiem.Getyyymmddmmss(),str);
                }
                catch (Exception ex)
                {
                    (FormDb.Db["Form1"] as Form1).textBox1.AppendText(HelpGetTiem.Getyyymmddmmss() + ":"+"Sokcet通信连接失败，请重新建立通信" + "\r\n");
                    throw new Exception(ex.Message + ":断开连接");
                }
            }
        }
        //发送消息方法
        public bool Sends(string message)
        {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message);

            if (socket != null)
            {
                try
                {
                    socket.Send(bytes);
                    return true;
                }catch (Exception ex)
                {
                    (FormDb.Db["Form1"] as Form1).textBox1.AppendText(HelpGetTiem.Getyyymmddmmss()+":通信已断开，无法发送消息，请检查线缆是否连接" + "\r\n");
                    throw new Exception(ex.Message+":断开连接");
                }
            }
            return false;
        }
    }
}
